package com.alibaba.csp.sentinel.dashboard.init;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.jpa.TbAiMonitorRule;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.repository.rule.InMemoryRuleRepositoryAdapter;
import com.alibaba.csp.sentinel.dashboard.repository.rule.JpaRuleRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class FlowRuleInit {

    private final Logger logger = LoggerFactory.getLogger(FlowRuleInit.class);

//    @Qualifier("jpaRuleRepository")
    @Autowired
    private JpaRuleRepository jpaRuleRepository;

    @Autowired
    private InMemoryRuleRepositoryAdapter<FlowRuleEntity> repository;

    @PostConstruct
    public void initFlowRule() {
        logger.info("限流规则同步>>>>>>>>>>>>>>>>>>>开始");
        List<TbAiMonitorRule> allRule = jpaRuleRepository.findAll();
        List<FlowRuleEntity> entityList = allRule.stream().map(rule -> {
            FlowRuleEntity flowRuleEntity = new FlowRuleEntity();
            BeanUtils.copyProperties(rule, flowRuleEntity);
            flowRuleEntity.setClusterConfig(rule.getClusterConfig2());
            return flowRuleEntity;
        }).collect(Collectors.toList());
        repository.init(entityList);
        logger.info("限流规则同步>>>>>>>>>>>>>>>>>>>结束");
    }

    @Scheduled(cron = "0/30 * * * * ?")
    public void task() {
        initFlowRule();
    }


}
